<template>
	<view class="page">
		<div class="header app-search-wrap shadow">
			<uni-search-bar class="search" cancelButton='none' @confirm="search" :focus="true" v-model="searchValue"
				@blur="blur" @focus="focus" @input="input" @cancel="cancel" @clear="clear">
			</uni-search-bar>
			<view @click="open" class="sbtn">选择类型</view>
			<view v-if="showAdmin" class="btn btn-im" @click="improtClick">导入</view>
			<view v-if="showAdmin" class="btn btn-ep" @click="download">导出</view>
		</div>
		

		<uni-popup ref="popup" type="dialog">
			<uni-popup-dialog mode="input" message="成功消息" :duration="2000" :before-close="true" :showClose="false"
				@close="close" @confirm="confirm">
		
				<picker-view :indicator-style="indicatorStyle" :value="typeValue" @change="bindChange"
					class="picker-view">
					<picker-view-column>
						<view class="item" v-for="(item,index) in typeList" :key="index">{{item.name}}</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in typeList[typeValue[0]].list" :key="index">{{item}}
						</view>
					</picker-view-column>
				</picker-view>
			</uni-popup-dialog>
		</uni-popup>

		
		<view v-for="(item, index) in listData" :key="index">
			<uni-list>
				<uni-list-item link @click="onClick($event,item.id)">
					<template slot="header">
						<view class="contents" >
							<text class="title" :class="{'red':item.overDate}">{{item.goodsModel}} - {{item.equipmentSeq}}</text>
							<text class="note">{{item.noteName}}</text>
						</view>
					</template>
					<template  slot="footer">
						<view  v-if="showAdmin && !isUserRole" class="btn btn-del" @click.stop="onClickDel($event,item.id)">
							<view>
								删除
							</view>
						</view>
					</template>
				</uni-list-item>
			</uni-list>
		</view>
		<uni-section  v-if="listData.length" class="bottom" padding>
			<uni-pagination :total="total" title="标题文字" :current="current" :pageSize="pageSize" @change="getListDate" />
		</uni-section>
		<uv-empty  v-if="!listData.length" mode="list" ></uv-empty>
	</view>
</template>

<script>
	import {
		log
	} from 'util';
	import {
		baseUrl
	} from '@/config.js';
	import { getToken } from '@/utils/auth'
	import store from '@/store'
	import storage from '@/utils/storage'
	import {
		uploadFile,
		exportFile,
		getLists,
		updateEq,
		deleteEq,
		getPositionType
	} from '@/api/me'
	export default {
		data() {
			return {
				indicatorStyle: `height: 50px;`,
				typeValue: [0, 0],
				typeList: [],
				showAdmin: false,
				searchValue: '',
				current: 1,
				total: 0,
				pageSize: 10,
				listData: [],
				globalConfig: getApp().globalData.config,
				isUserRole: true,
			}
		},
		onLoad() {
			// this.getListDate();
			
			let vuex_roles = storage.get('vuex_roles');
			if (vuex_roles.includes('admin') || vuex_roles.includes('system')) this.showAdmin = true;
			console.log(store.getters.isUserRole, '12312312')
			this.isUserRole =store.getters.isUserRole
			this.getTypeDetail();
			this.$refs.popup.open();
		},
		onShow() {
			this.getListDate();
		},
		methods: {
			close() {
				// TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
				// ...
				this.$refs.popup.close()
			},
			open() {
				this.$refs.popup.open()
			},
			bindChange: function(e) {
				const val = e.detail.value;
				this.typeValue = [val[0], val[1]];
			},
			/**
			 * 点击确认按钮触发
			 * @param {Object} done
			 * @param {Object} value
			 */
			confirm(value) {
				// 输入框的值
				console.log(value)
				// TODO 做一些其他的事情，手动执行 close 才会关闭对话框
				// ...
				this.$refs.popup.close();
				this.getListDate();
			},
			getTypeDetail(e) {
				// let res = await getList()
				getPositionType().then(res => {
					console.log(res)
					let typeList = [];
					for (let key in res) {
						typeList.push({
							name: key,
							list: res[key]
						})
					}
					this.typeList = typeList;
					debugger
				}).catch((err) => {
					uni.showToast({
						title: err || '获取类型失败',
						icon: 'error'
					})
				})
			},
			improtClick(e) {
				   let baseUrl = this.globalConfig.baseUrl;
				   wx.chooseMessageFile({
				     count: 1, // 默认9
				     type: 'file', // 可以指定为'all'、'image'、'video'、'audio'、'file'
				     success: function (res) {
				       const tempFilePaths = res.tempFiles[0].path; // 获取到临时文件路径
					      wx.uploadFile({
					        url: baseUrl + '/system/equipment/importData', // 服务器接口地址
							header: {
								Authorization: 'Bearer ' + getToken(),
								contentType: "multipart/form-data"
							},
					        filePath: tempFilePaths,
					        name: 'file', // 对应服务器端接收文件字段名
					        formData: {
					          // 文件上传额外携带的信息，如用户标识等
					          updateSupport: "true"
					        },
					        success: function (res) {
								debugger
					          const data = res.data;
							  uni.showToast({
								  title: '上传成功',
								  icon: "none"
							  	
							  })
					          // 上传成功处理逻辑
					        },
					        fail: function (err) {
					          // 上传失败处理逻辑
					        }
					      });
				     }
				   })

			},
			download(file) {
				uni.showLoading({
					title: '下载中'
				});
				 wx.downloadFile({
					header: {
						Authorization: 'Bearer ' + getToken()
					},
				       url: baseUrl + '/system/equipment/export',
				       success: function(res) {
						   uni.hideLoading()
				         wx.openDocument({
				           filePath: res.tempFilePath,
						   showMenu: true, 
				           success: function() {
				             console.log('文件打开成功');
				           },
				           fail: function() {
				             console.error('文件打开失败');
				           }
				         });
				       },
				       fail: function() {
				         console.error('下载文件失败');
				       }
				     });
					 return;
				//下载文件
				uni.downloadFile({ //只能是GET请求
					url: baseUrl + '/system/equipment/export', //请求地址(后台返回的码流地址)
					success: (res) => {
						//下载成功
						if (res.statusCode === 200) {
							//保存文件
							let tempFile = res.tempFilePath;
							//保存成功之后 打开文件
							uni.getFileSystemManager().saveFile({
								tempFilePath: tempFile,
								// filePath: wx.env.USER_DATA_PATH + '/' + '上传成员.pdf',//自定义文件名
								success(res) {
									console.log(res)
									uni.openDocument({
										filePath: res.savedFilePath,
										showMenu: true, //是否可以分享
										success: (res) => {
											uni.hideLoading()
											console.log(res);
										},
										fail: (e) => {
											uni.showToast({
												title: '打开失败',
												icon: "error"
											})
										}
									})

								}
							})
						}
					},
					fail: (e) => {
						console.log(e, '文件下载失败')
						uni.showToast({
							title: '文件下载失败',
							icon: "error",
						})
					}
				});
			},
			getListDate(e) {
				if (e) {
					let {
						type,
						current
					} = e;
					console.log(type, current)
					this.current = current;
				}

				// let res = await getList()
				getLists({
					pageSize: this.pageSize,
					pageNum: this.current,
					searchValue: this.searchValue,
					goodsType: this.typeList[this.typeValue[0]].name,
					goodsName: this.typeList[this.typeValue[0]].list[this.typeValue[1]],
				}).then(res => {
					res.rows.forEach(item => item.noteName = `${item.position}`);
					console.log(res)
					this.listData = res.rows;
					this.total = res.total;
				})
			},
			onClick(e, id) {
				console.log(e, id);
				let ob = this.listData.find(item => item.id === id);
				uni.navigateTo({
					url: `/pages/work/device-detail/index?id=${id}`,
					success: function(res) {
						// 通过eventChannel向被打开页面传送数据
						res.eventChannel.emit('acceptDataFromOpenerPage', ob)
					}
				})

			},
			onClickDel(e, id) {
				uni.showModal({
					title: "提示",
					content: "确认删除？",
					success: (res) => {
						if (res.confirm) {
							deleteEq({
								id
							}).then(res => {
								this.getListDate()
								console.log(res.msg)
								uni.showToast({
									title: res.msg,
									duration: 2000
								});
							})
						}
					}
				})

			},
			search(res) {
				uni.showToast({
					title: '搜索：' + res.value,
					icon: 'none'
				})
			},
			input(res) {
				this.searchValue = res;
				this.getListDate()
			},
			clear(res) {
				// uni.showToast({
				// 	title: 'clear事件，清除值为：' + res.value,
				// 	icon: 'none'
				// })
			},
			cancel(res) {
				// uni.showToast({
				// 	title: '点击取消，输入值为：' + res.value,
				// 	icon: 'none'
				// })
			},

		},
		onBackPress() {
			// #ifdef APP-PLUS
			plus.key.hideSoftKeybord();
			// #endif
		}

	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
		padding-top: 110rpx;
	}

	.header {
		display: flex;
		align-items: center;
		justify-content: space-around;

	}

	.btn {
		padding: 20rpx;
		margin: -20rpx -20rpx -20rpx 0;

		&>view {
			@include item-btn($after-color, rgba($after-color, 0.7));
		}
	}

	.btn-add {
		&>view {
			@include item-btn($theme-color, rgba($theme-color, 0.7));
		}
	}

	.btn-del {
		&>view {
			@include item-btn(#f84b4c, rgba(#f84b4c, 0.6));
		}
	}
	
	.contents {
		    display: flex;
		    padding-right: 8px;
		    flex: 1;
		    color: #3b4144;
		    flex-direction: column;
		    justify-content: space-between;
		    overflow: hidden;
			.title {
				    font-size: 14px;
				    color: #3b4144;
				    overflow: hidden;
			}
			.note {
				margin-top: 6rpx;
				    color: #999;
				    font-size: 12px;
				    overflow: hidden;
			}
	}
	.red {
		color: #f84b4c !important;
	}
	.picker-view {
		width: 750rpx;
		height: 600rpx;
		margin-top: 20rpx;
		.item {
			line-height: 100rpx;
			text-align: center;
		}
	}
	

</style>